<template>
  <div class="ranking-management">
    <div class="header">
      <h2>랭킹 관리</h2>
      <div class="controls">
        <el-select v-model="selectedPeriod" @change="fetchRankings" style="width: 120px; margin-right: 12px;">
          <el-option label="전체" value="all" />
          <el-option label="일간" value="daily" />
          <el-option label="주간" value="weekly" />
          <el-option label="월간" value="monthly" />
        </el-select>
        <el-button type="primary" @click="showCreateDialog">새 랭킹 추가</el-button>
      </div>
    </div>

    <el-table :data="rankings" v-loading="loading" stripe>
      <el-table-column prop="rankPosition" label="순위" width="80" />
      <el-table-column label="채널" width="200">
        <template #default="{ row }">
          <div class="channel-info">
            <img :src="row.channel.avatarUrl || '/default-avatar.png'" class="avatar" />
            <div>
              <div class="channel-name">{{ row.channel.name }}</div>
              <div class="owner-info">{{ row.channel.owner?.nickname || row.channel.owner?.loginId }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="viewCount" label="시청자 수" width="120">
        <template #default="{ row }">
          {{ row.viewCount.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="giftCount" label="선물 수량" width="120">
        <template #default="{ row }">
          {{ row.giftCount.toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="점수" width="100" />
      <el-table-column label="유형" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isManual ? 'success' : 'info'">
            {{ row.isManual ? '수동' : '자동' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="업데이트 시간" width="180">
        <template #default="{ row }">
          {{ formatDate(row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="작업" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="editRanking(row)">편집</el-button>
          <el-button size="small" type="danger" @click="deleteRanking(row)">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchRankings"
        @current-change="fetchRankings"
      />
    </div>

    <!-- 생성/편집 대화상자 -->
    <el-dialog
      v-model="showDialog"
      :title="isEditing ? '순위 편집' : '순위 추가'"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="채널" prop="channelId">
          <el-select
            v-model="form.channelId"
            placeholder="채널을 선택하세요"
            style="width: 100%"
            filterable
            :loading="channelLoading"
          >
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="기간" prop="period">
          <el-select v-model="form.period" style="width: 100%">
            <el-option label="전체" value="all" />
            <el-option label="일간" value="daily" />
            <el-option label="주간" value="weekly" />
            <el-option label="월간" value="monthly" />
          </el-select>
        </el-form-item>
        <el-form-item label="순위 위치" prop="rankPosition">
          <el-input-number v-model="form.rankPosition" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="시청자 수" prop="viewCount">
          <el-input-number v-model="form.viewCount" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="선물 수량" prop="giftCount">
          <el-input-number v-model="form.giftCount" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="시청 시간" prop="watchSeconds">
          <el-input-number v-model="form.watchSeconds" :min="0" style="width: 100%" />
          <div class="form-tip">단위: 초</div>
        </el-form-item>
        <el-form-item label="점수" prop="score">
          <el-input-number v-model="form.score" :min="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">취소</el-button>
        <el-button type="primary" @click="saveRanking" :loading="saving">저장</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

interface Channel {
  id: string
  name: string
  avatarUrl?: string
  owner?: {
    id: string
    loginId: string
    nickname?: string
  }
}

interface Ranking {
  id: string
  channelId: string
  period: string
  rankPosition: number
  viewCount: number
  giftCount: number
  watchSeconds: number
  score: number
  isManual: boolean
  createdAt: string
  updatedAt: string
  channel: Channel
}

const loading = ref(false)
const rankings = ref<Ranking[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const selectedPeriod = ref('all')

const showDialog = ref(false)
const isEditing = ref(false)
const saving = ref(false)
const formRef = ref()

const form = ref({
  id: '',
  channelId: '',
  period: 'all',
  rankPosition: 1,
  viewCount: 0,
  giftCount: 0,
  watchSeconds: 0,
  score: 0,
})

const rules = {
  channelId: [{ required: true, message: '채널을 선택하세요', trigger: 'change' }],
  period: [{ required: true, message: '기간을 선택하세요', trigger: 'change' }],
  rankPosition: [{ required: true, message: '순위 위치를 입력하세요', trigger: 'blur' }],
}

const channels = ref<Channel[]>([])
const channelLoading = ref(false)

// 获取排名列表
const fetchRankings = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      period: selectedPeriod.value,
    }
    const response = await request.get('/api/admin/rankings', { params })
    rankings.value = response.data.rankings
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('순위 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 获取所有频道
const fetchChannels = async () => {
  channelLoading.value = true
  try {
    const response = await request.get('/api/admin/channels', {
      params: { limit: 200 } // 선택을 위해 더 많은 채널 가져오기
    })
    channels.value = response.data.channels || []
  } catch (error) {
    console.error('채널 가져오기 실패:', error)
    ElMessage.error('채널 목록 가져오기 실패')
  } finally {
    channelLoading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEditing.value = false
  form.value = {
    id: '',
    channelId: '',
    period: selectedPeriod.value,
    rankPosition: 1,
    viewCount: 0,
    giftCount: 0,
    watchSeconds: 0,
    score: 0,
  }
  // 确保有频道数据
  if (channels.value.length === 0) {
    fetchChannels()
  }
  showDialog.value = true
}

// 编辑排名
const editRanking = (ranking: Ranking) => {
  isEditing.value = true
  form.value = {
    id: ranking.id,
    channelId: ranking.channelId,
    period: ranking.period,
    rankPosition: ranking.rankPosition,
    viewCount: ranking.viewCount,
    giftCount: ranking.giftCount,
    watchSeconds: ranking.watchSeconds,
    score: ranking.score,
  }
  // 确保有频道数据，如果没有则获取
  if (channels.value.length === 0) {
    fetchChannels()
  } else {
    // 确保当前频道在选项中
    const currentChannel = channels.value.find(c => c.id === ranking.channelId)
    if (!currentChannel) {
      channels.value.push(ranking.channel)
    }
  }
  showDialog.value = true
}

// 保存排名
const saveRanking = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    if (isEditing.value) {
      await request.put(`/api/admin/rankings/${form.value.id}`, form.value)
      ElMessage.success('업데이트 성공')
    } else {
      await request.post('/api/admin/rankings', form.value)
      ElMessage.success('생성 성공')
    }

    showDialog.value = false
    await fetchRankings()
  } catch (error) {
    ElMessage.error('저장 실패')
  } finally {
    saving.value = false
  }
}

// 删除排名
const deleteRanking = async (ranking: Ranking) => {
  try {
    await ElMessageBox.confirm('이 순위를 삭제하시겠습니까？', '삭제 확인', {
      type: 'warning',
    })

    await request.delete(`/api/admin/rankings/${ranking.id}`)
    ElMessage.success('삭제 성공')
    await fetchRankings()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchRankings()
  fetchChannels()
})
</script>

<style scoped>
.ranking-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  align-items: center;
}

.channel-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.channel-name {
  font-weight: 500;
}

.owner-info {
  font-size: 12px;
  color: #999;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>
